<template>
  <view class="container">
    <view class="tab-box">
      <view :class="['tab', status == -1 ? 'active' : '']" @click="changeStatus(-1)">全部</view>
      <view :class="['tab', status == 0 ? 'active' : '']" @click="changeStatus(0)">待支付</view>
      <view :class="['tab', status == 1 ? 'active' : '']" @click="changeStatus(1)">进行中</view>
      <view :class="['tab', status == 2 ? 'active' : '']" @click="changeStatus(2)">已完成</view>
      <view :class="['tab', status == 3 ? 'active' : '']" @click="changeStatus(3)">审核中</view>
      <view :class="['tab', status == 4 ? 'active' : '']" @click="changeStatus(4)">已取消</view>
    </view>

    <view class="order-list">
      <navigator hover-class="none" :url="'/pages/order_detail/order_detail?id=' + item.id + '&index=' + index" class="order" v-for="(item, index) in list" :key="index">
        <view class="row">
          <view class="name">{{ item.service_name }}</view>
          <view class="status">{{ item.status_desc }}</view>
        </view>
        <view class="row">
          <view class="price">{{ item.pay_price }}元/次</view>
          <view class="time">{{ item.pay_time }}</view>
        </view>

        <view class="btn-box" v-if="item.status == 0">
          <view class="btn" @click.stop="cancel(item.id, index)">取消</view>
          <view class="btn pay" @click.stop="pay(item.id, index)">确认支付</view>
        </view>
      </navigator>
    </view>

    <view id="mask" v-if="show_login" @click.stop>
      <view class="mask-content" @click.stop>
        <form @submit="formSubmit" class="main-content">
          <view class="title">完善资料</view>
          <button open-type="chooseAvatar" @chooseavatar="getAvatar" class="avatar-btn">
            <image class="btnImg" :src="avatar_path" mode="aspectFill"></image>
          </button>
          <input type="text" :value="avatar" name="avatar" style="display: none">

          <view class="row">
            <view class="left">昵称</view>
            <input type="nickname" @focus="this.showLoginModel = true" @input="this.showLoginModel = true" :value="username" name="nickname" class="input" placeholder="请输入昵称">
          </view>

          <view class="row" style="border-top: none">
            <view class="left">手机号</view>
            <button open-type="getPhoneNumber" :plain="true" @getphonenumber="getPhoneNumber" class="mobile-btn" v-if="!mobile">获取手机号</button>
            <block v-else>
              <input type="number" :value="mobile" name="mobile" style="display: none">
              <view class="input">{{ mobile }}</view>
            </block>
          </view>

          <view class="agree-box">
            <button hover-class="none" :type="'mini'" :plain="true" class="item agree-btn" open-type="agreePrivacyAuthorization">
              <checkbox :checked="is_agree" @click="doAgree" class="checkbox round color" color="#32A4FF" style="background: #FFF;border: none"/>
            </button>

            <view class="box">
              阅读并接受
              <text class="text" @click="openPrivacy">{{ privacyContractName }}</text>
            </view>
          </view>

          <input type="text" :value="openid" name="openid" style="display: none">

          <view class="btn-box">
            <button :plain="true" class="button cancel" @click="this.show_login = false">取消</button>
            <button form-type="submit" class="button save">保存</button>
          </view>
        </form>
      </view>
    </view>
  </view>
</template>

<script>
import http from '@/utils/http'

export default {
  data() {
    return {
      list: [],
      status: -1,
      page: 1,
      pagesize: 10,
      show_login: false,
      privacyContractName: '《陪诊预约隐私保护指引》',
      is_agree: false,
      avatar: 0,
      avatar_path: '../../static/images/default_avatar.png',
      mobile: '',
      username: '',
      showLoginModel: false,
      openid: '',
    };
  },

  onLoad: function () {
    var user_id = uni.getStorageSync('user_id');
    if (user_id) {
      this.orderList();
    } else {
      uni.showLoading({
        title: '自动登录中...',
        mask: true
      })

      uni.login({
        success: result => {
          var code = result.code;

          this.$http.post('/index/Api/openidToUserid', {code}).then(res => {
            uni.hideLoading();
            if (res.data.result === 1) {
              var user_id = res.data.data;
              uni.setStorageSync('user_id', user_id)

              this.orderList();
            } else {
              this.show_login = true;
            }
          })
        }
      })
    }

  },

  onReachBottom() {
    this.orderList(this.page + 1);
  },

  methods: {
    changeStatus: function (status) {
      this.status = status;
      this.page = 1;
      this.orderList();
    },

    cancel: function (id, index) {
      uni.showModal({
        title: '提示',
        content: '确定要取消订单吗？',
        success: res => {
          if (res.confirm) {
            this.$http.post('/index/Api/cancelOrder', {id}).then(res => {
              if (res.data.result === 1) {
                if (this.status == -1) {
                  this.list[index].status = 4;
                  this.list[index].status_desc = '已取消';
                } else {
                  this.list.splice(index, 1);
                }
              }
            })
          }
        }
      })
    },

    pay: function (id, index) {
      var timestamp = Date.parse(new Date()),//该值除以1000就是当前的时间戳,
        sync_timestamp = uni.getStorageSync('timestamp') ? uni.getStorageSync('timestamp') : 0,//获取时间戳缓存,
        now_timestamp = timestamp / 1000,
        long_time = now_timestamp - sync_timestamp;//距离上次点击按钮经过的时长（秒）

      if (long_time > 3) {
        //将当前时间戳存为缓存
        uni.setStorageSync('timestamp', timestamp / 1000);

        uni.showLoading({
          title: '支付中...',
          mask: true
        })

        this.$http.post('/index/Api/pay', {id}).then(res => {
          uni.removeStorageSync('timestamp');
          if (res.data.result == 1) {
            var {order_sn, pay_data} = res.data.data;
            /********主要代码********/
            if (pay_data) {
              uni.getProvider({
                service: 'payment',
                success: result => {
                  var provider = result.provider;
                  if (provider) {
                    uni.requestPayment({
                      provider: provider,
                      orderInfo: {order_sn},
                      timeStamp: pay_data.timeStamp,
                      nonceStr: pay_data.nonceStr,
                      package: pay_data.package,
                      signType: pay_data.signType,
                      paySign: pay_data.paySign,
                      success: res => {
                        uni.hideLoading();

                        if (res.data.result === 1) {
                          if (this.status == -1) {
                            this.list[index].status = 3;
                            this.list[index].status_desc = '审核中';
                          } else {
                            this.list.splice(index, 1);
                          }
                        }
                      },
                      fail: function (res) {
                        uni.showToast({
                          title: '取消支付',
                          icon: 'none'
                        })
                      }
                    })
                  } else {
                    uni.showToast({
                      title: '取消支付',
                      icon: 'none'
                    })
                  }
                }
              });
            }
            /********主要代码********/
          } else {
            uni.hideLoading();
            this.$common.doErrorResult(res);
          }
        })
      }
    },

    openPrivacy: function () {
      uni.openPrivacyContract()
    },

    getAvatar: function (e) {
      var {avatarUrl} = e.detail;

      uni.uploadFile({
        url: http.config.baseURL + '/Upload/UploadFile/uniUploadPicture', //服务端图片上传接口地址
        filePath: avatarUrl,
        name: 'download',
        formData: {},
        success: res => {
          res = JSON.parse(res.data)
          if (res.result === 1) {
            uni.showToast({
              title: '上传头像成功'
            })
            this.showLoginModel = true;
            this.avatar_path = res.data.path;
            this.avatar = res.data.id;
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        },
        fail: err => {
          setTimeout(() => {
            uni.hideLoading();
            uni.showToast({
              title: '图片上传失败',
              icon: 'none'
            })
          }, 500)
        }
      })
    },

    getPhoneNumber: function (e) {
      var code = e.detail.code;
      this.$http.post('/index/Api/getMobile', {code}).then(res => {
        if (res.data.result === 1) {
          this.mobile = res.data.data
        } else {
          this.$common.doErrorResult(res)
        }
      })
    },

    doAgree: function () {
      this.is_agree = !this.is_agree;
    },

    formSubmit: function (e) {
      var formData = e.detail.value,
        timestamp = Date.parse(new Date()),//该值除以1000就是当前的时间戳,
        sync_timestamp = uni.getStorageSync('timestamp') ? uni.getStorageSync('timestamp') : 0,//获取时间戳缓存,
        now_timestamp = timestamp / 1000,
        long_time = now_timestamp - sync_timestamp;//距离上次点击按钮经过的时长（秒）,

      if (!this.is_agree) {
        uni.showToast({
          title: '请阅读并勾选小程序隐私保护指引',
          icon: 'none'
        })
        return;
      }

      uni.showLoading({
        title: '保存中...',
        mask: true
      })

      if (long_time > 3) {
        //将当前时间戳存为缓存
        uni.setStorageSync('timestamp', timestamp / 1000);

        uni.login({
          success: result => {
            var code = result.code;

            this.$http.post('/index/Api/getOpenid', {code}).then(res => {
              if (res.data.result === 1) {
                formData.openid = res.data.data;

                this.$http.post('/Index/Api/login', formData).then(res => {
                  uni.removeStorageSync('timestamp');
                  uni.hideLoading();

                  if (res.data.result === 1) {
                    var user_id = res.data.data;
                    uni.setStorageSync('user_id', user_id)

                    this.show_login = false;

                    this.orderList();
                  } else {
                    this.$common.doErrorResult(res);
                  }
                })
              } else {
                this.$common.doErrorResult(res);
              }
            })
          }
        })
      }
    },

    orderList: function (incPage = 0) {
      var page = incPage ? incPage : this.page;

      uni.showLoading({
        title: '数据加载中...',
        mask: true
      })

      this.$http.post('/index/Api/orderList', {
        user_id: uni.getStorageSync('user_id'),
        status: this.status,
        page: page,
        pagesize: this.pagesize
      }).then((res) => {
        if (res.data.result == 1) {
          if (page == 1) {
            this.list = res.data.data;
          } else {
            // 加载更多
            var list = this.list;

            for (var i = 0; i < res.data.data.length; i++) {
              list.push(res.data.data[i]);
            }

            this.list = list;
            this.page = page;
          }

          setTimeout(() => {
            uni.hideLoading();
          }, 500)
        } else {
          uni.hideLoading();
          if (page == 1) {
            this.list = [];
          } else {
            this.$common.doErrorResult(res);
          }
        }
      })
    },
  },
}
</script>

<style lang="scss">
.container {
  .tab-box {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    display: flex;
    background: #fff;
    height: 100rpx;
    align-items: center;
    justify-content: space-between;
    padding: 0 20rpx;

    .active {
      color: $main-color;
    }
  }

  .order-list {
    display: flex;
    flex-direction: column;
    padding: 0 20rpx;
    margin-top: 120rpx;

    .order {
      display: flex;
      flex-direction: column;
      width: calc(100% - 40rpx);
      background: #fff;
      border-radius: 20rpx;
      padding: 20rpx;
      margin-bottom: 20rpx;

      .row {
        display: flex;
        width: 100%;
        justify-content: space-between;
        margin-bottom: 50rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .name {
          width: 70%;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          font-size: 32rpx;
          color: $main-color;
        }

        .status {
          font-size: 32rpx;
        }

        .price {
          color: #EF835E;
        }

        .time {
          color: $main-blank;
          font-size: 24rpx;
        }
      }

      .btn-box {
        display: flex;
        justify-content: flex-end;
        padding-top: 20rpx;
        border-top: 2rpx solid #F2F6F7;

        .btn {
          background: #ccc;
          color: #fff;
          padding: 14rpx 30rpx;
          border-radius: 10rpx;
          margin-left: 20rpx;
        }

        .pay {
          background: #4cd964;
        }
      }
    }
  }
}
</style>

